<?php
namespace app\service;

use think\facade\Cache;
use think\facade\Db;

class QueueService
{
    protected $queueKey = 'queue:numbers';
    protected $webSocketService;

    public function __construct()
    {
        $this->webSocketService = new WebSocketService();
    }

    // 取号
    public function getNumber()
    {
        $number = Cache::incr('queue:counter');
        Cache::rPush($this->queueKey, $number);
        return $number;
    }

    // 叫号
    public function callNumber()
    {
        $number = Cache::lPop($this->queueKey);
        if ($number) {
            $this->webSocketService->pushToAll(['type' => 'call', 'number' => $number]);
            $this->saveToDatabase($number);
        }
        return $number;
    }

    // 获取当前排队状态
    public function getQueueStatus()
    {
        return Cache::lRange($this->queueKey, 0, -1);
    }

    // 在 QueueService 中添加数据库操作
    protected function saveToDatabase($number)
    {
        // 假设有一个 queue_history 表
        Db::name('queue_history')->insert([
            'number' => $number,
            'called_at' => date('Y-m-d H:i:s')
        ]);
    }
    
}